
export class Utils {
    private static instance: Utils = null;

    /** interval 字典 */
    private _objInterval: any = null;
    /** timeout 字典 */
    private _objTimeout: any = null;

    static getInstance(){
        if( !Utils.instance ){
            Utils.instance = new Utils()
        }
        return Utils.instance 
    }
    
    GetRandom(){
        return Math.floor( Math.random() * 100000000 )
    }

    //数字中间加逗号
    MilliFormat(num) {
        return num && num.toString()
            .replace(/\d+/, function(s){
                 return s.replace(/(\d)(?=(\d{3})+$)/g, '$1,')
             })
    }
        
    
    /**
     * 获取时间戳
     * @returns 时间戳
     */
    getTime(){
        return new Date().getTime()
    }
    /**
     * 获取当前时间
     * @returns 当前日期
     */
    public getNowDate(){
        const date = new Date()
        let month: string | number = date.getMonth() + 1
        let strDate: string | number = date.getDate()
        if(month <= 9){
            month = '0' + month
        }
        if(strDate <= 9){
            strDate = '0' + strDate 
        }
        let strHour: string | number = date.getHours()
        if(strHour <= 9){
            strHour = '0' + strHour 
        }

        let strMin: string | number = date.getMinutes()
        if(strMin <= 9){
            strMin = '0' + strMin 
        }
        
        let sec: string | number = date.getSeconds()
        if(sec <= 9){
            sec = '0' + sec 
        }
        let millSec: string | number = date.getMilliseconds()
        if(millSec <= 9){
            millSec = '0' + millSec 
        }
        return date.getFullYear() + "-" + month + "-" + strDate + " " + strHour + ":" + strMin + ":" + sec + "." + millSec
    }

    public webCopyString(str){
        var input = str;
        const el = document.createElement("textarea");
        el.value = input;
        el.setAttribute('readonly','');
        el.style.contain = 'strict';
        el.style.position = 'absolute';
        el.style.left = '-9999px';
        el.style.fontSize = '12pt'; // Prevent zooming on iOS

        const selection = getSelection();
        var originalRange = null;
        if (selection.rangeCount > 0) {
            originalRange = selection.getRangeAt(0);
        }
        document.body.appendChild(el);
        el.select();
        el.selectionStart = 0;
        el.selectionEnd = input.length;

        var success = false;
        try {
            success = document.execCommand('copy');
        } catch (err) {}

        document.body.removeChild(el);

        if (originalRange) {
            selection.removeAllRanges();
            selection.addRange(originalRange);
        }

        return success;
    }

    formatTime(timeStr: string){
        let ret = ""
        let arr1 = timeStr.split("T")
        let arr2 = arr1[1].split("+")
        let hour = arr2[0].substring(0,8)
        ret = arr1[0] + " " + hour
        return ret
    }

   
    
    addInterval(callFun: Function, time: number, intervalKey: string): void {
        if (this._objInterval == null) this._objInterval = {};
        if (this._objInterval[intervalKey]) clearInterval(this._objInterval[intervalKey]);
        let interval = setInterval(callFun, time);
        this._objInterval[intervalKey] = interval;
    }

    /** 清除节点计时器 */
    removeInterval(intervalKey: string) {
        if (this._objInterval != null) {
            if (this._objInterval[intervalKey]) clearInterval(this._objInterval[intervalKey]);
        }
    }

    
    /** 
     * 添加计时器 
     * intervalKey 计时器的key
     * */
    addTimeout(callFun: Function, time: number, timeoutKey: string): void {
        if (this._objTimeout == null) this._objTimeout = {};
        if (this._objTimeout[timeoutKey]) clearTimeout(this._objTimeout[timeoutKey]);
        let timeout = setTimeout(callFun, time);
        this._objTimeout[timeoutKey] = timeout;
    }

    /** 清除节点计时器 */
    removeTimeout(timeoutKey: string) {
        if (this._objTimeout != null) {
            if (this._objTimeout[timeoutKey]) clearTimeout(this._objTimeout[timeoutKey]);
        }
    }

    /**太长显示... 默认中文4个字 英文8个 */
    textFromat(str, maxChars?: number) {
        maxChars = maxChars || 4;
        var toCodePoint = function (unicodeSurrogates) {
            var r = [], c = 0, p = 0, i = 0;
            while (i < unicodeSurrogates.length) {
                var pos = i;
                c = unicodeSurrogates.charCodeAt(i++);//返回位置的字符的 Unicode 编码 
                if (c == 0xfe0f) {
                    continue;
                }
                if (p) {
                    var value = (0x10000 + ((p - 0xD800) << 10) + (c - 0xDC00));
                    r.push({
                        v: value,
                        pos: pos,
                    }); //计算4字节的unicode
                    p = 0;
                } else if (0xD800 <= c && c <= 0xDBFF) {
                    p = c; //如果unicode编码在oxD800-0xDBff之间，则需要与后一个字符放在一起
                } else {
                    r.push({
                        v: c,
                        pos: pos
                    }); //如果是2字节，直接将码点转为对应的十六进制形式
                }
            }
            return r;
        }
        maxChars *= 2;

        var codeArr = toCodePoint(str);
        var numChar = 0;
        var index = 0;
        for (var i = 0; i < codeArr.length; ++i) {
            var code = codeArr[i].v;
            var add = 1;
            if (code >= 128) {
                add = 2;
            }
            //如果超过了限制，则按上一个为准
            if (numChar + add > maxChars) {
                break;
            }
            index = i;
            //累加
            numChar += add;
        }
        if (codeArr.length - 1 == index) {
            return str;
        }
        var more = "..." ? 1 : 0;
        return str.substring(0, codeArr[index - more].pos + 1) + "...";
    }
}

export  let utils : Utils = Utils.getInstance()